<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-input v-model="input.noticeNum" placeholder="请输入编号" style="width: 200px;"></el-input>
      </el-form-item>
      <el-button type="primary" icon="el-icon-search" @click="page()">查询</el-button>
      <el-button type="default" @click="resetData()">清空</el-button>
    </el-form>
    <div>
      <el-button type="primary" @click="exportExcel">导出</el-button>
    </div>
          <!-- <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload> -->
          
          <!-- 欢迎你:{{username}}
          <div>
      <el-avatar :src="imageUrl"></el-avatar>
          </div> -->



          <el-upload
                        :show-file-list="false"
                        :before-upload="beforeUpload"
                        :on-success="onSuccess"
                        :on-error="onError"
                        :disabled="importDisabled"
                        style="display: inline-flex;margin-right: 10px;"
                        action="http://39.99.160.25:8088/notices/web/importNoticesExcel"
                        name="userFiles"
                        >
                    <el-button size="small" :disabled="importDisabled" type="success" :icon="importDataIcon">
                       {{importDataText}}
                    </el-button>
                </el-upload>

     


    <el-table :data="noticesList" style="width: 100%">
      <el-table-column fixed prop="noticeNum" label="公告编号" width="80"></el-table-column>
      <el-table-column prop="noticeTitle" label="公告标题" width="100"></el-table-column>
      <el-table-column prop="noticeContent" label="公告内容" width="100"></el-table-column>
      <el-table-column prop="noticeTime" label="公告时间" width="100"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  methods: {
    //搜索框输入搜索
    selectByNoticeNum() {
      const _this = this;
      var arr = [];
      axios({
        url:
          "http://39.99.160.25:8088/notices/web/select_notice_id?noticeNum=" +
          this.input.noticeNum,
        method: "get"
      }).then(function(res) {
        //将对象插入数组中
        var obj = res.data.data.selectdata;
        if (res.data.data.selectdata == null) {
          _this.noticesList = null;
        } else {
          arr.push({
            noticeNum: res.data.data.selectdata.noticeNum,
            noticeTitle: res.data.data.selectdata.noticeTitle,
            noticeContent: res.data.data.selectdata.noticeContent,
            noticeTime: res.data.data.selectdata.noticeTime
          });
          _this.noticesList = arr;
        }
      });
    },

    //搜索框搜索
    page() {
      if (this.input.noticeNum == "") {
        this.selectall();
      } else {
        this.selectByNoticeNum();
      }
    },

    resetData() {
      //清空的方法
      //表单输入项数据清空
      this.input = {};
      // this.page()
      this.selectall();
    },

    exportExcel() {
      //  this.loading = true;

      // axios({
      //   url:'http://39.99.160.25:8088/notices/web/exportNoticesExcel',
      //   method:'post',
      //   responseType:'blob',
      //   // params
      // }).then(function (resp)
      // {
      //   const link = document.createElement('a')
      //    let blob = new Blob([resp.data], { type: 'application/msexcel' });
      //   link.style.display = 'none'
      //   link.href = URL.createObjectURL(blob);
      //   link.setAttribute('attachment; filename=', fileName + '.xls');
      //    document.body.appendChild(link);
      //    link.click();
      //   document.body.removeChild(link);
      //    this.loading = false;

      //   // let url = window.URL.createObjectURL(resp.data);
      //   //  let link = document.createElement('a');
      //   //  link.style.display = 'none';
      //   //  link.href = url;
      //   //  link.setAttribute('download', 'filename=201117115547.xls');
      //   //  document.body.appendChild(link);
      //   //  link.click()

      // //   let blob = new Blob([resp.data], {
      // //   type: 'text/plain;charset=UTF-8'
      // // }); // 2.获取请求返回的response对象中的blob 设置文件类型，这里以excel为例
      // // let url = window.URL.createObjectURL(blob); // 3.创建一个临时的url指向blob对象

      // // // 4.创建url之后可以模拟对此文件对象的一系列操作，例如：预览、下载
      // // let a = document.createElement("a");
      // // a.href = url;
      // // a.download = "download.xls";
      // // a.click();
      // // // 5.释放这个临时的对象url
      // // window.URL.revokeObjectURL(url);

      // }
      // )

      // const a = document.createElement('a')
      // a.href = axios({
      //   url:'http://39.99.160.25:8088/notices/web/exportNoticesExcel',
      //   method:"post"
      //   })
      // a.download = "download.xls";
      // a.click()

      axios({
        url: "http://39.99.160.25:8088/notices/web/exportNoticesExcel",
        method: "post",
        //  async: true,
        // withCredentials :false,

        responseType: "blob"
      }).then(function(res) {
        //  headers:{
        //   connection: keep-alive;
        //   Content-Disposition : "attachment; filename=201121190002.xls"
        //  }
        console.log(res);
        //xing
        //   var blob = new Blob([res], {type: 'application/msexcel'})
        //   var downloadElement = document.createElement('a');
        //   downloadElement.style.display = 'none';
        //   var href = window.URL.createObjectURL(blob); //创建下载的链接
        //   downloadElement.href = href;
        //   downloadElement.download = '导出文件.xls'; //下载后文件名
        //   downloadElement.setAttribute('download',response.getResponseHeader('content-disposition'));
        //   document.body.appendChild(downloadElement);
        //   downloadElement.click(); //点击下载
        //   document.body.removeChild(downloadElement); //下载完成移除元素
        //  window.URL.revokeObjectURL(href); //释放掉blob对象

        // const link = document.createElement('a')
        // let blob = new Blob([res], { type: 'application/octer-stream' });
        // link.style.display = 'none'
        // link.href = URL.createObjectURL(blob);
        // link.setAttribute('download', fileName + '.xls');
        // document.body.appendChild(link);
        // link.click();
        // document.body.removeChild(link)

        // const blob = new Blob([res], { type: 'application/octet-stream' })
        // //IE10以上支持blob但是依然不支持download
        // if ('download' in document.createElement('a')) {
        //   //支持a标签download的浏览器
        //   const link = document.createElement('a') //创建a标签link.download = '标注数据.xls' //a标签添加属性
        //   link.style.display = 'none'
        //   link.href = URL.createObjectURL(blob)
        //   document.body.appendChild(link)
        //   link.click() //执行下载
        //   URL.revokeObjectURL(link.href) //释放url
        //   document.body.removeChild(link) //释放标签
        // }

        let url = window.URL.createObjectURL(new Blob([res.data])); //转换为可用URl地址
        let link = document.createElement("a"); //创建a标签
        link.style.display = "none"; //使之不可见
        link.href = url; //赋URL地址
        //link.setAttribute("download", res.data.fileName+'.xls'); //设置下载属性、以及文件名
        link.setAttribute("download", "通知列表导出" + ".xls");
        document.body.appendChild(link); //将a标签插至页面中
        link.click(); //强制触发a标签事件
      });
    },

    handleEdit(row) {
      this.$router.push({
        path: "/updateNotice",
        query: {
          noticeNum: row.noticeNum
        }
      });
    },

    selectall() {
      const _this = this;
      axios({
        method: "get",
        url: "http://39.99.160.25:8088/notices/web/notice_list",
        data: {},
        headers: {}
      }).then(function(resp) {
        console.log(resp);

        _this.noticesList = resp.data.data.list;
      });
    },
    handleDelete(row) {
      const _this = this;
      console.log(row);
      axios({
        method: "delete",
        url:
          "http://39.99.160.25:8088/notices/web/delete_notice?noticeNum=" +
          row.noticeNum,
        data: {},
        headers: {
          // "Authorization":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ7XCJpZFwiOjksXCJ1c2VybmFtZVwiOm51bGwsXCJwaG9uZVwiOm51bGwsXCJhZGRyZXNzXCI6bnVsbCxcInJlbWFya1wiOm51bGwsXCJhdXRob3JpdHlcIjowLFwicGFzc3dvcmRcIjpcIjExMTExMVwiLFwiaGVhZF9wb3J0cmFpdFwiOm51bGwsXCJhcHBpZFwiOm51bGwsXCJzY29wZVwiOm51bGwsXCJzdGF0ZVwiOm51bGwsXCJ3aGV0aGVyX2RlbGV0ZVwiOm51bGwsXCJpZGVudGl0eV9pZFwiOlwiMTExMTExXCIsXCJjcmVhdGVfdGltZVwiOm51bGwsXCJ1cGRhdGVfdGltZVwiOm51bGwsXCJkZWxldGVfdGltZVwiOm51bGwsXCJvcmRlcnNMaXN0XCI6bnVsbH0iLCJleHAiOjE2MDUwOTU5OTZ9.TBEM_7Ti_Mm_UB9vD236lPstsqMjWAawBaBDFSp6oN0"
          Authorization: sessionStorage.getItem("token")
        }
      }).then(function(resp) {
        if (resp.data.data.msg == "删除成功") {
          _this.$alert("《" + row.noticeNum + "》删除成功！", "消息", {
            confirmButtonText: "确定",
            callback: action => {
              // _this.$router.push('/notices')
              window.location.reload();
            }
          });
        }
      });
    },

onError() {
                this.importDataText = '导入数据';
                this.importDataIcon = 'el-icon-upload2';
                this.importDisabled = false;
               // this.initEmps();
                this.$message.success("导入失败！");
            },
            // 导入文件成功后回调
            onSuccess() {
            	// 成功后文本修改为原来的导入数据
                this.importDataText = '导入数据';
                // 图标修改
                this.importDataIcon = 'el-icon-upload2';
                // 将上传组件改为允许使用
                this.importDisabled = false;
                // 调用刷新数据的方法
                 this.selectall();
                //this.initEmps();
                // message 弹出消息
                this.$message.success("导入成功！");
            },
            // 上传文件调用
            beforeUpload() {
              // axios({
              //   url:'',
              //   method:'post',

              // }).then(function(res){

              // })
            	// 将文本修改为正在导入
                this.importDataText = '正在导入';
                // 修改其图标
                this.importDataIcon = 'el-icon-loading';
                // 将其上传组件暂时禁用
                this.importDisabled = true;
            }



    //  handleAvatarSuccess(res, file) {
    //     this.imageUrl = URL.createObjectURL(file.raw);
    //   },

    //   beforeAvatarUpload(file) {
    //     const isJPG = file.type === 'image/jpeg';
    //     const isLt2M = file.size / 1024 / 1024 < 2;

    //     if (!isJPG) {
    //       this.$message.error('上传头像图片只能是 JPG 格式!');
    //     }
    //     if (!isLt2M) {
    //       this.$message.error('上传头像图片大小不能超过 2MB!');
    //     }
    //     return isJPG && isLt2M;
    //   }

  },
  data() {
    return {


importDataText: '导入数据',
		// 导入按钮的图标
		importDataIcon: 'el-icon-upload2',
		// 导入按钮是否被禁用
		importDisabled: false,




      username:sessionStorage.getItem('username'),
       imageUrl: sessionStorage.getItem('head_portrait'),
      show: true,
      filename: "",
      input: {
        noticeNum: ""
      },
      noticesList: [
        {
          noticeNum: "1",
          noticeTitle: "111",
          noticeContent: "111",
          noticeTime: "111"
        },
        {
          noticeNum: "2",
          noticeTitle: "222",
          noticeContent: "222",
          noticeTime: "222"
        },
        {
          noticeNum: "3",
          noticeTitle: "333",
          noticeContent: "333",
          noticeTime: "333"
        },
        {
          noticeNum: "4",
          noticeTitle: "444",
          noticeContent: "444",
          noticeTime: "444"
        }
      ]
    };
  },
  created() {
    // const _this = this;
    // axios({
    //   method: "get",
    //   url: "http://39.99.160.25:8088/notices/web/notice_list",
    //   data: {},
    //   headers: {}
    // }).then(function(resp) {
    //   console.log(resp);

    //   _this.noticesList = resp.data.data.list;
    // });
    this.selectall();
  }
};
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>